package com.sl.service;

import com.sl.pojo.Document;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;


import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.time.LocalDateTime;

@Slf4j
@Service
public class StorageService {
    @Autowired
    private DocumentService documentService;

    private Path rootLocation;

    /**
     * 存储一个文件对象
     * @param contentLength  文件长度
     * @param contentType    文件类型
     * @param fileName       文件索引名
     * @param uploader       上传者
     * @param desc           文件描述
     * @return
     */
    public Document store( long contentLength, String contentType,
                          String fileName ,String uploader,String desc,String fileNameNew) {
        log.info(  contentLength + ">>>>>>>>" + contentType + ">>>>>>>>"
                + fileName + "uploader>>>>>>>>" + uploader + ">>>>>>>>" + desc);

            log.info("文件存在>>>>存储数据库");
            Document document = new Document();
            document.setDocName(fileName);
            document.setDocSize((int) contentLength);
            document.setDocType(contentType);
            document.setDocUuid(fileNameNew);
            document.setStorageUrl("kong");
            document.setUploadTime(LocalDateTime.now());
            document.setUploader(uploader);
            document.setDocDesc(desc);
            //储存方式 0 是公开。。1 是私人
            document.setStorageType(0);
            //是否被删除0 存在   1逻辑删除
            document.setDeleted(0);
            documentService.addDocument(document);
            return document;
    }

    public Path load(String filename) {
        return rootLocation.resolve(filename);
    }

    public Resource loadAsResource(String filename) {
        //加载为资源
        try {
            Path file = load(filename);
            //获取文件绝对路径
            Resource resource = new UrlResource(file.toUri());
            //如果 文件 1存在  且 2可读
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                return null;
            }
        } catch (MalformedURLException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }


}
